import ujson as json
import time
from machine import Pin
from yzlink import yzMqttLinker

class DemoDevice():
    def __init__(self):
        self._led1 = Pin(4,Pin.OUT)
        self._led2 = Pin(5,Pin.OUT)
        self._sw = [Pin(4,Pin.OUT),Pin(5,Pin.OUT)]
        
        self._mqtt = yzMqttLinker("1.14.48.246","user","mqttpwd",debug=True)
        #self._mqtt.addTopicBackFunc(b"led1",self.topicLED1)
        #self._mqtt.addTopicBackFunc(b"led2",self.topicLDE2)
        
        self._mqtt.addTopicBackFunc(b"online",self.onLineQuery)
        self._mqtt.addTopicBackFunc(b"newtitle",self.onChangeName)
        self._mqtt.addTopicBackFunc(b"switch/change",self.onSwitchChange)
        self._mqtt.addTopicBackFunc(b"switch/query",self.querySwitchStatus)
        self._mqtt.addTopicBackFunc(b"timer/update",self.updateTimerList)
        
    def updateTimerList(self,topic,payload):
        print('update timer list')
        print(payload)
        data = json.loads(payload)
        print("timer list len:{} id:{}".format(data["length"],data["id"]))
        for x in data["timeritem"]:
            print("="*8)
            
            status = ""
            for s in x["ts"]:
                temp_str = "index:{},value:{}".format(s["index"],s["sw_status"])
                status += temp_str
            print('timeout:{} ; type:{} ;status:[{}]'.format(x["to"],x["tp"],status))
        
        self._mqtt.publish(b'timer/update_re',payload)
        
    def querySwitchStatus(self,topic,payload):
        print('query switch')
        #ret = {'values':[0,1]}
        for index,switch in enumerate(self._sw):
            ret = {'index':index,'value':switch.value()}
            self._mqtt.publish(b'switch/change_re',json.dumps(ret))
            print(ret)
        #self._mqtt.publish(b'switch/query_re',json.dumps(ret))
        
    def onSwitchChange(self,topic,payload):
        print('switch change:')
        print(payload)
        switch_status = json.loads(payload)
        value = int(switch_status['value'])
        index = int(switch_status['index'])
        self._sw[index].value(value)
        print('index:{} switch status:{}'.format(switch_status['index'],switch_status['value']))
        self._mqtt.publish(b'switch/change_re',payload)
        
    def onLineQuery(self,topic,payload):
        print('controller online query')
        ret = {
            'name':'esp8266_device22',
            'type':'2*2S'
            }
        self._mqtt.publish(b'online_re',json.dumps(ret))
        
    def onChangeName(self,topic,payload):
        data = json.loads(payload)
        print('change device name:{}'.format(data['name']))
        self._mqtt.publish(b'title_re',json.dumps(data))
        

    def topicLED1(self,topic,payload):
        print(topic)
        print(payload)
        data = json.loads(payload)
        print(data)
        if 'value' in data.keys():
            led = int(data['value'])
            if led:
                self._led1.on()
            else:
                self._led1.off()

    def topicLDE2(self,topic,payload):
        print(topic)
        print(payload)
        data = json.loads(payload)
        print(data)
        if 'value' in data.keys():
            led = int(data['value'])
            if led:
                self._led2.on()
            else:
                self._led2.off()

    def run(self):
        try:
            while True:
                self._mqtt.loop()
        except KeyboardInterrupt as e:
            print("Exit.")
            self._mqtt.close()

if __name__ == "__main__":
    DemoDevice().run()